/**
 * 
 */
package com.game.codec;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

/**
 * @author lushouzhi
 * 
 */
public class ProtocolBuilder {

	private ByteBuffer store = ByteBuffer.allocate(64);

	public Object build() {
		int length=store.position() + 4;
		ByteBuffer ret = ByteBuffer.allocate(length);
		store.flip().rewind();
		ret.putInt(store.remaining() + 4);
		ret.put(store);
		store.clear();
		return ret.flip();
	}

	/**
	 * clear all data
	 */
	public void clear() {

	}

	public void setByte(byte data) {
		store.put(data);
	}

	public void setInt(int data) {
		store.putInt(data);
	}

	public void setLong(long data) {
		store.putLong(data);
	}

	public void setShort(short data) {
		store.putShort(data);
	}

	public void setString(String s) {
		try {
			byte[] b = s.getBytes("UTF-8");
			store.putShort((short) b.length);
			store.put(b);
		} catch (UnsupportedEncodingException ex) {
		}
	}

	public void setStringArray(String[] sArray) {
		short strNum = (short) sArray.length;
		short totalLen = 2;
		byte[][] data = new byte[strNum][];
		for (int i = 0; i < strNum; i++) {
			try {
				data[i] = sArray[i].getBytes("UTF-8");
			} catch (UnsupportedEncodingException ex) {
				data[i] = new byte[0];
			}
			totalLen += (data[i].length + 2);
		}
		store.putShort(totalLen);
		store.putShort(strNum);
		for (byte[] arr : data) {
			store.putShort((short) arr.length);
			store.put(arr);
		}
	}

	public void setIntArray(int[] array) {
		short length = (short) array.length;
		store.putShort((short) (length * 4));
		for (int i : array) {
			store.putInt(i);
		}
	}

	// set long array | Add on 20100719
	public void setLongArray(long[] array) {
		int length = array.length;
		store.putShort((short) (length * 8));
		for (long i : array) {
			store.putLong(i);
		}
	}

	public void setShortArray(short[] array) {
		int length = array.length;
		store.putShort((short) (length * 2));
		for (short s : array) {
			store.putShort(s);
		}
	}

	public void setByteArray(byte[] data) {
		store.putShort((short) (data.length));
		store.put(data);
	}

}
